package com.zhaolang.qogir.ui.processed;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.suke.widget.SwitchButton;
import com.zhaolang.qogir.R;
import com.zhaolang.qogir.application.QogirApplication;
import com.zhaolang.qogir.bean.OrderFinishedBean;
import com.zhaolang.qogir.cache.SharePreCacheHelper;
import com.zhaolang.qogir.ui.BaseFragment;
import com.zhaolang.qogir.ui.adapter.FragmentProcessFinishedAdapter;
import com.zhaolang.qogir.util.HttpConstant;
import com.zhaolang.qogir.util.Slog;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class FragmentProcessedFinished extends BaseFragment implements PullToRefreshBase.OnRefreshListener2<ListView> {

    private PullToRefreshListView pullListView;
    private ListView listView;
    private FragmentProcessFinishedAdapter finishedAdapter;
    private SwitchButton btn_printer_setting;
    private OkHttpClient okHttpClient = new OkHttpClient();
    private final static int MSG_BASE = 0x30;
    private final static int MSG_FRESH_ORDER_UI = MSG_BASE + 1;
    private final static int MSG_TOAST_FRESH = MSG_BASE + 2;
    private final static int MSG_REFRESH_ORDER_ITEM = MSG_BASE + 3;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_FRESH_ORDER_UI:
                    List<OrderFinishedBean> listBean = (List<OrderFinishedBean>) msg.obj;
                    finishedAdapter.setData(listBean);
                    finishedAdapter.notifyDataSetChanged();
                    break;
                case MSG_TOAST_FRESH:
                    Toast.makeText(mContext, R.string.network_error, Toast.LENGTH_SHORT).show();
                    break;
                case MSG_REFRESH_ORDER_ITEM:
                    pullListView.setRefreshing();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        setContentView(R.layout.fragment_processed_finished);
        initView();
        return getContentView();
    }

    @Override
    public void onResume() {
        super.onResume();
        pullListView.setRefreshing();
    }

    private void initView() {
        pullListView = findViewById(R.id.pullListView);
        listView = pullListView.getRefreshableView();
        pullListView.setOnRefreshListener(this);
        pullListView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        finishedAdapter = new FragmentProcessFinishedAdapter(mContext);
        pullListView.setAdapter(finishedAdapter);
        pullListView.setOnItemClickListener(finishedAdapter);
        btn_printer_setting = findViewById(R.id.btn_processed_print_working);
        btn_printer_setting.setChecked(false);
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        new GetDataTask().execute();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        new GetDataTask().execute();
    }

    private class GetDataTask extends AsyncTask<Void, Void, String> {

        @Override
        protected String doInBackground(Void... params) {
            readAllFilterOrder();
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
            // Call onRefreshComplete when the list has been refreshed.
            pullListView.onRefreshComplete();
        }
    }

    /**
     * read all today filter order by system
     */
    private void readAllFilterOrder() {
        String url = HttpConstant.getAllFinishedOrder(null) + "?SHOP_ID=15651723391";
        final Request request = new Request.Builder().url(url).build();
        if (okHttpClient != null) {
            okHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Slog.e("onFailure: " + e.getMessage());
                    handler.sendEmptyMessage(MSG_TOAST_FRESH);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String body = response.body().string();
                    Slog.i("onResponse: " + body);
                    parsingFinishedOrder(body);
                }
            });
        }
    }

    private void setFinishOrder(String deliveryId, String orderId) {
        String url = HttpConstant.obtainFinishedOrder(null) + "?DELIVERY_ID=" + deliveryId + "&ORDER_ID=" + orderId;
        final Request request = new Request.Builder().url(url).build();
        if (okHttpClient != null) {
            okHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(Call call, IOException e) {
                    Slog.e("onFailure: " + e.getMessage());
                    handler.sendEmptyMessage(MSG_TOAST_FRESH);
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    String body = response.body().string();
                    Slog.i("onResponse: " + body);
                    parsingNewOrder(body);
                }
            });
        }
    }

    private void parsingNewOrder(String body) {
        try {
            JSONObject jsonObject = new JSONObject(body);
            if (jsonObject.optString("status").equals("success")) {
                handler.sendEmptyMessage(MSG_REFRESH_ORDER_ITEM);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void parsingFinishedOrder(String body) {
        List<OrderFinishedBean> orderList = new ArrayList<>();
        try {
            JSONObject jsonObject = new JSONObject(body);
            /* parse product class bean from json object */
            if (jsonObject.optString("status").equals("success")) {
                String classValues = jsonObject.optString("orderContent");
                Object object = new JSONTokener(classValues).nextValue();
                if (object instanceof JSONObject) {
                    OrderFinishedBean bean = new OrderFinishedBean();
                    bean.setOrderId(((JSONObject) object).optString("orderId"));
                    bean.setTel(((JSONObject) object).optString("userTel"));
                    bean.setTime(((JSONObject) object).optString("orderTime"));
                    bean.setAddress(((JSONObject) object).optString("addrName"));
                    //加入本机注册的账户信息
                    bean.setDeliveryId(SharePreCacheHelper.getUserID(QogirApplication.getMainContext()));
                    bean.setName(((JSONObject) object).optString("userName"));
                    bean.setOrderStatus(Integer.valueOf(((JSONObject) object).optString("status")));
                    orderList.add(bean);
                } else if (object instanceof JSONArray) {
                    JSONArray jsonArray = (JSONArray) object;
                    for (int m = 0; m < jsonArray.length(); m++) {
                        JSONObject details = jsonArray.getJSONObject(m);
                        OrderFinishedBean bean = new OrderFinishedBean();
                        bean.setOrderId(details.optString("orderId"));
                        bean.setTel(details.optString("tel"));
                        bean.setTime(details.optString("orderTime"));
                        bean.setAddress(details.optString("addrName"));
                        bean.setDeliveryId(SharePreCacheHelper.getUserID(getContext()));
                        bean.setName(details.optString("userName"));
                        bean.setOrderStatus(Integer.valueOf(details.optString("status")));
                        orderList.add(bean);
                    }
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        handler.sendMessage(Message.obtain(handler, MSG_FRESH_ORDER_UI, orderList));
    }
}